import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/*
过程：
1.创建一个构造方法，创建指定线程数，并让这些线程执行任务
2.有一个阻塞队列用来添加任务
3.创建一个submit方法添加新任务
 *
 */
class MyPool {
    //list存储线程
    private List<Thread> list = new ArrayList<>();
    //阻塞队列存储1000个任务
    private final BlockingQueue<Runnable> blockingDeque = new ArrayBlockingQueue<>(1000);
    // 这里开启n个线程，这些线程不断的从阻塞队列的队首获取任务，一直执行
    public MyPool(int n) {
        for (int i=0; i<n; i++) {
            // 生成一个线程t
            Thread t = new Thread(()-> {
                while (true) {
                    Runnable runnable = null;
                    try {
                        runnable = blockingDeque.take();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    runnable.run();
                }
            });
            list.add(t);
            t.start();
        }
    }
    public void submit(Runnable runnable) throws InterruptedException {
        blockingDeque.put(runnable);
    }
}

public class pool {
    public static void main(String[] args) throws InterruptedException {
        //线程池里核心线程数为5
        MyPool myPool = new MyPool(5);
        //模拟1000个任务
        for (int i=0; i<1000; i++) {
            // 模拟遍历1000个任务, 第n个任务
            int n = i;
            myPool.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println("当前线程是" + Thread.currentThread().getName() + "完成任务为" + n);
                }
            });
        }
    }
}



